package com.anmong.parser.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;


@Service
public class JsonParserService {

    public String parseJson(String arrayStr){
        if (StringUtils.isBlank(arrayStr)){
            throw new RuntimeException("原文不能为空!");
        }
        JSONArray jsonArray = JSONUtil.parseArray(arrayStr);
        StringBuilder output = new StringBuilder();
        if (!jsonArray.isEmpty()){
            for (int i = 0; i < jsonArray.size();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                // 判断是三段值还是两段值
                String describeFieldKey = "";
                if (jsonObject.size() == 2){
                    describeFieldKey = jsonObject.keySet().toArray(new String[0])[1];
                }
                else if (jsonObject.size() == 3){
                    describeFieldKey = jsonObject.keySet().toArray(new String[0])[2];
                }
                else {
                    throw new RuntimeException("格式不符合要求，请让ai重新推理");
                }
                String lineStr = jsonObject.getStr(describeFieldKey);
                if (StringUtils.isBlank(lineStr)){
                    throw new RuntimeException("第" + i+1 + "行推理结果为空,请让ai重新推理.");
                }
                output.append(lineStr);
                //去除最后一行的换行
                if (i != jsonArray.size() -1){
                    output.append("\n");
                }
            }
        }
        return output.toString();

    }


}
